use std::slice; 

use super::my_err::MyErr;

/// 解析图片上的二维码
#[allow(dead_code)]
pub fn read_qrcode(img_path: &str) -> Result<String, MyErr> {
    let img = image::open(img_path).map_err(|_| MyErr::Msg("读取图片信息失败".to_string()))?;

    // Use default decoder
    let decoder = bardecoder::default_decoder();

    let results = decoder.decode(&img);

    if let Some(rs) = results.iter().next() {
        log::debug!("\n\n\n{:?}\n\n\n", rs);
        match rs {
            Ok(s) => Ok(s.to_string()),
            Err(_) => Err(MyErr::Msg("二维码解析失败！".to_string())),
        }
    } else {
        Err(MyErr::Msg("图片上无法读取到有效的二维码".to_string()))
    }
}

/// base64 转 jpg 图片
pub fn base64_to_jpg(base64_str: &str) -> Result<(image::DynamicImage, usize), MyErr> {
    // 把base64字符串转为图片，需要把字符串头的 data:image/jpeg;base64, 删除掉。共23个字符。所以 &base64_str[23..]
    let img_var = rbase64::decode(&base64_str[23..]).map_err(|_| MyErr::Msg("图片转换失败，请检查是否是合法的base64字符串".to_string()))?;

    let ptr: *const u8 = img_var.as_ptr();
    let len: usize = img_var.len();
    let array: &[u8] = unsafe { slice::from_raw_parts(ptr, len) }; 

    let img = image::load_from_memory(array).map_err(|_| MyErr::Msg("图片转换失败，请核对base64数据是否是图片格式".to_string()))?;

    //let mut file = File::create("output.jpg")?;
    //let _ = img.write_to(&mut file, image::ImageFormat::Jpeg).map_err(|_| MyErr::Msg("图片保存失败".to_string()));

    Ok((img, len))
}
